package com.zbkj.dal.config;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @author heyi
 */
@Slf4j
@Component
public class AsyncCompletableFuture implements ApplicationContextAware {

    private static ThreadPoolTaskExecutor taskExecutor;

//    private static MyMessageHelper myMessageHelper;

    public static void runAsync(Runnable runnable) {
        runAsyncBase(runnable, false, null);
    }

    public static void runAsync(Runnable runnable, String title) {
        runAsyncBase(runnable, false, title);
    }

    public static void runAsyncAndNoticeOnError(Runnable runnable) {
        runAsyncBase(runnable, true, null);
    }

    public static void runAsyncAndNoticeOnError(Runnable runnable, String title) {
        runAsyncBase(runnable, true, title);
    }


    private static void runAsyncBase(Runnable runnable, boolean notice, String title) {
        if (Objects.isNull(runnable)) {
            return;
        }
        final String traceId = StringUtils.defaultString(MDC.get("traceId"), IdUtil.nanoId(25));
        CompletableFuture.runAsync(() -> {
            MDC.put("traceId", traceId);
            try {
                runnable.run();
            } catch (Exception e) {
                log.error("异步方法执行失败", e);
                if (BooleanUtils.isTrue(notice)) {
//                    myMessageHelper.sendMarkDownMessage(StrUtil.format("异步方法[{}]执行失败：{}", StrUtil.emptyIfNull(title), e.getMessage()));
                }
            } finally {
                MDC.clear();
            }
        }, taskExecutor);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        taskExecutor = applicationContext.getBean(ThreadPoolTaskExecutor.class);
//        myMessageHelper = applicationContext.getBean(MyMessageHelper.class);
    }
}
